import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class DatePickerComponent extends StatefulWidget {
  final String title;
  final double? width;
  final DateTime? initialDateTime;
  final String? data;
  final Function(DateTime? selectedDate)? onChanged;

  const DatePickerComponent({
    Key? key,
    required this.title,
    this.width,
    this.initialDateTime,
    this.data,
    this.onChanged,
  }) : super(key: key);

  @override
  State<DatePickerComponent> createState() => _DatePickerComponentState();
}

class _DatePickerComponentState extends State<DatePickerComponent> {
  late DateTime _selectedDate;
  // 滚动控制器（用于控制三个选择器的同步滚动）
  late FixedExtentScrollController _yearController;
  late FixedExtentScrollController _monthController;
  late FixedExtentScrollController _dayController;

  @override
  void initState() {
    super.initState();
    // 初始化日期
    _selectedDate = _parseDateFromData() ?? widget.initialDateTime ?? DateTime.now();

    // 初始化滚动控制器
    _yearController = FixedExtentScrollController(
      initialItem: _selectedDate.year - 2025,
    );
    _monthController = FixedExtentScrollController(
      initialItem: _selectedDate.month - 1,
    );
    _dayController = FixedExtentScrollController(
      initialItem: _selectedDate.day - 1,
    );
  }

  // 解析data字符串
  DateTime? _parseDateFromData() {
    if (widget.data == null || widget.data!.isEmpty) return null;
    try {
      final parts = widget.data!.split('-');
      if (parts.length != 3) return null;
      return DateTime(
        int.parse(parts[0]),
        int.parse(parts[1]),
        int.parse(parts[2]),
      );
    } catch (e) {
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: widget.width,
        margin: const EdgeInsets.symmetric(vertical: 10),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Padding(
            //   padding: const EdgeInsets.only(bottom: 16),
            //   child: Text(
            //     widget.title,
            //     style: const TextStyle(
            //       fontSize: 16,
            //       fontWeight: FontWeight.w500,
            //       color: Colors.black87,
            //     ),
            //   ),
            // ),
            // const SizedBox(height: 20),
            _buildDatePickerWithLines(),
          ],
        ),
      ),
    );
  }

  // 带选中线的容器
  Widget _buildDatePickerWithLines() {
    return Container(
      height: 170,
      child: Stack(
        children: [
          // 上分隔线
          Positioned(
            top: 55,
            left: 0,
            right: 0,
            height: 1,
            child: Container(color: Colors.grey[300]),
          ),
          // 下分隔线
          Positioned(
            top: 115,
            left: 0,
            right: 0,
            height: 1,
            child: Container(color: Colors.grey[300]),
          ),
          // 选择器主体
          _buildDatePicker(),
        ],
      ),
    );
  }

  // 构建年月日选择器
  Widget _buildDatePicker() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 年选择器
        _buildCustomPicker(
          controller: _yearController,
          minValue: 2025,
          maxValue: 2100,
          value: _selectedDate.year,
          suffix: "年",
          onChanged: (value) => _updateDate(year: value),
        ),
        // 月选择器
        _buildCustomPicker(
          controller: _monthController,
          minValue: 1,
          maxValue: 12,
          value: _selectedDate.month,
          suffix: "月",
          onChanged: (value) => _updateDate(month: value),
        ),
        // 日选择器
        _buildCustomPicker(
          controller: _dayController,
          minValue: 1,
          maxValue: _getDaysInMonth(_selectedDate.year, _selectedDate.month),
          value: _selectedDate.day,
          suffix: "日",
          onChanged: (value) => _updateDate(day: value),
        ),
      ],
    );
  }

  // 自定义选择器（完全消除原生灰色背景）
  Widget _buildCustomPicker({
    required FixedExtentScrollController controller,
    required int minValue,
    required int maxValue,
    required int value,
    required String suffix,
    required Function(int) onChanged,
  }) {
    return Container(
      width: 80,
      height: 170,
      // 关键：使用ClipRect消除边缘模糊效果
      child: ClipRect(
        child: ListWheelScrollView.useDelegate(
          controller: controller,
          itemExtent: 60, // 每个选项高度
          magnification: 1.2, // 中间项放大
          overAndUnderCenterOpacity: 0.6, // 上下项透明度
          physics: const FixedExtentScrollPhysics(), // 固定滚动效果
          onSelectedItemChanged: (index) {
            onChanged(minValue + index);
          },
          childDelegate: ListWheelChildBuilderDelegate(
            childCount: maxValue - minValue + 1,
            builder: (context, index) {
              final num = minValue + index;
              final isSelected = num == value;

              return Center(
                child: Text(
                  '$num$suffix',
                  style: TextStyle(
                    fontSize: 16,
                    color: isSelected ? Colors.black : Colors.grey[600],
                    fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                  ),
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  // 更新日期
  void _updateDate({int? year, int? month, int? day}) {
    setState(() {
      _selectedDate = DateTime(
        year ?? _selectedDate.year,
        month ?? _selectedDate.month,
        day ?? _selectedDate.day,
      );
      // 更新日选择器的最大天数（月份变化时）
      if (month != null) {
        _dayController.jumpToItem(
            (_selectedDate.day - 1).clamp(0, _getDaysInMonth(_selectedDate.year, _selectedDate.month) - 1)
        );
      }
    });
    widget.onChanged?.call(_selectedDate);
  }

  // 获取当月天数
  int _getDaysInMonth(int year, int month) {
    if (month == 2) {
      return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 ? 29 : 28;
    }
    const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    return daysInMonth[month - 1];
  }

  @override
  void dispose() {
    // 释放控制器
    _yearController.dispose();
    _monthController.dispose();
    _dayController.dispose();
    super.dispose();
  }
}